package com.wedu.modules.test.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wedu.common.utils.PageUtils;
import com.wedu.common.utils.Query;
import com.wedu.common.utils.R;
import com.wedu.modules.sys.dao.SysUserDao;
import com.wedu.modules.sys.entity.SysUserEntity;
import com.wedu.modules.test.dao.StudentScoreDao;
import com.wedu.modules.test.entity.StudentScoreEntity;
import com.wedu.modules.test.entity.StudentVO;
import com.wedu.modules.test.service.StudentScoreService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service("studentScoreService")
public class StudentScoreServiceImpl extends ServiceImpl<StudentScoreDao, StudentScoreEntity> implements StudentScoreService {

    @Autowired
    private SysUserDao sysUserDao;

    @Autowired
    private StudentScoreDao studentScoreDao;

    @Override
    public PageUtils queryPagestu(Map<String, Object> params,Long userId) {
        Integer student = sysUserDao.selectById(userId).getStudent();
        //判断是否是学生
        // 老师
        if (student == 1) {
            String realName = (String) params.get("realName");
            String examTime = (String) params.get("examTime");

            IPage<StudentScoreEntity> page = this.page(
                    new Query<StudentScoreEntity>().getPage(params),
                    new QueryWrapper<StudentScoreEntity>()
                            .eq("is_deleted", 0)
                            .orderByDesc("create_time")
            );
            //获取user表中有真名的学生信息
            List<StudentVO> studentVOList = baseMapper.queryAllRealName();

            //将搜索到的学生信息以学号、名字存到map集合中
            Map<Long, String> stuMap = new HashMap<>();
            for (StudentVO studentVO : studentVOList) {
                stuMap.put(studentVO.getSid(), studentVO.getRealName());
            }
            /**
             * 将Data类型转换为String类型*/
            List<String> timeList = new ArrayList<>();
            for (StudentVO studentVO : studentVOList) {
                Date date = studentVO.getExamTime();
                Instant instant = date.toInstant();
                ZoneId zone = ZoneId.systemDefault();
                //Date转换为LocalDateTime
                LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
                DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String strDate = dtf.format(localDateTime);
                if (!timeList.contains(strDate)){
                    timeList.add(strDate);
                }
            }
            /**
             * 遍历学生姓名
             * */
            List<String> nameList = new ArrayList<>();
            for (StudentVO studentVO : studentVOList) {
                nameList.add(studentVO.getRealName());
            }

            List<Map<String, Object>> studentscorelist = new ArrayList<>();
            /**
             * 写一个wrapper语句搜索examTime相同的数据*/
            QueryWrapper<StudentScoreEntity> wrapper = new QueryWrapper<StudentScoreEntity>()
                    .eq(StringUtils.isNotBlank(examTime),"exam_time",examTime);
            List<StudentScoreEntity> studentScoreEntityList = baseMapper.selectList(wrapper);
            //考试时间框
            if (StringUtils.isNotBlank(examTime) && StringUtils.isBlank(realName)){  //时间有，名字空
                if (timeList.contains(examTime)){
                    for (StudentScoreEntity studentScoreEntity : studentScoreEntityList) {
                        studentscorelist.add(selectLike(studentScoreEntity, stuMap.get(studentScoreEntity.getSid())));
                    }
                }
            }else if (StringUtils.isBlank(examTime) && StringUtils.isNotBlank(realName)){  //时间空 名字有
                for (StudentScoreEntity record : page.getRecords()) {
                    //模糊查询，查找输入字符串是否包含输入的字符&&
                    if (stuMap.get(record.getSid()).contains(realName)) {
                        studentscorelist.add(selectLike(record, stuMap.get(record.getSid())));
                    }
                }
            }else if (StringUtils.isNotBlank(examTime) && StringUtils.isNotBlank(realName)){  //时间有，名字有
                for (StudentScoreEntity studentScoreEntity : studentScoreEntityList) {
                    List<Long> sid = new ArrayList<>();
                    for (StudentVO studentVO : studentVOList) {
                        if(studentVO.getRealName().contains(realName))
                        {   //去重
                            if (!sid.contains(studentVO.getSid())){
                                sid.add(studentVO.getSid());
                            }
                        }
                    }
                    for (Long aLong : sid) {
                        if(studentScoreEntity.getSid().equals(aLong)){
                            studentscorelist.add(selectLike(studentScoreEntity, stuMap.get(studentScoreEntity.getSid())));
                        }
                    }
                }
            }else if (StringUtils.isBlank(examTime) && StringUtils.isBlank(realName)){  //时间空，名字空
                for (StudentScoreEntity studentScoreEntity : studentScoreEntityList) {
                    studentscorelist.add(selectLike(studentScoreEntity, stuMap.get(studentScoreEntity.getSid())));
                }
            }


            //分页设置
            IPage<Map<String, Object>> studentVOIPage = new Page<>();
            studentVOIPage.setTotal(page.getTotal());
            studentVOIPage.setSize(page.getSize());
            studentVOIPage.setPages(page.getPages());
            studentVOIPage.setRecords(studentscorelist);
            studentVOIPage.setCurrent(page.getCurrent());
            return new PageUtils(studentVOIPage);

        }else if (student == 0){

            String examTime = (String) params.get("examTime");
            String mathsScore = (String) params.get("maths"); //0~59
            List<StudentVO> studentVOList = new ArrayList<>();
            List<StudentVO> voList = baseMapper.queryAllRealName();
            for (StudentVO studentVO : voList) {
                if (studentVO.getSid().equals(userId)){
                    studentVOList.add(studentVO);
                }
            }
            //data转化成字符串
            List<String> timeList = new ArrayList<>();
            for (StudentVO studentVO : studentVOList) {
                Date date = studentVO.getExamTime();
                Instant instant = date.toInstant();
                ZoneId zone = ZoneId.systemDefault();
                //Date转换为LocalDateTime
                LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
                DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String strDate = dtf.format(localDateTime);
                if (!timeList.contains(strDate)){
                    timeList.add(strDate);
                }
            }

            IPage<StudentScoreEntity> page = this.page(
                    new Query<StudentScoreEntity>().getPage(params),
                    new QueryWrapper<StudentScoreEntity>()
                            .eq("is_deleted", 0)
                            .orderByDesc("create_time")
            );



            Map<Long, String> stuMap = new HashMap<>();
            for (StudentVO studentVO : studentVOList) {
                stuMap.put(studentVO.getSid(), studentVO.getRealName());
            }

            List<Map<String, Object>> studentscorelist = new ArrayList<>();

            QueryWrapper<StudentScoreEntity> wrapper = new QueryWrapper<StudentScoreEntity>()
                    .eq(StringUtils.isNotBlank(examTime),"exam_time",examTime)
                    .eq("sid",userId);

            List<StudentScoreEntity> studentScoreEntityList = baseMapper.selectList(wrapper);
            //考试时间框
            if (StringUtils.isNotBlank(examTime)){
                if (timeList.contains(examTime)){
                    for (StudentScoreEntity studentScoreEntity : studentScoreEntityList) {//size:1
                        studentscorelist.add(selectLike(studentScoreEntity, stuMap.get(studentScoreEntity.getSid())));
                    }
                }
            }else {
                for (StudentScoreEntity studentScoreEntity : studentScoreEntityList) {
                    studentscorelist.add(selectLike(studentScoreEntity, stuMap.get(studentScoreEntity.getSid())));
                }
            }

//            if (StringUtils.isNotBlank(mathsScore)){
//                String[] maths = mathsScore.split("~");
//                Integer min = Integer.valueOf(maths[0]);  //0
//                Integer max = Integer.valueOf(maths[1]);  //59
//                wrapper.between(StudentScoreEntity::getMaths,min,max);
//            }

//            IPage<StudentVO> studentVOIPage = new Page<>();
            IPage<Map<String, Object>> studentVOIPage = new Page<>();
            studentVOIPage.setTotal(page.getTotal());
            studentVOIPage.setSize(page.getSize());
            studentVOIPage.setPages(page.getPages());
            studentVOIPage.setRecords(studentscorelist);
            studentVOIPage.setCurrent(page.getCurrent());
            return new PageUtils(studentVOIPage);
        }
        return null;
    }


    /**
     * 新增学生信息
     * */
    @Override
    public R savestu(StudentScoreEntity studentScoreEntity) {
        List<StudentVO> studentVOList = baseMapper.queryAllRealName();
        List<Long> sidList = new ArrayList<>();
        //遍历学生信息，将学号存入数组
        for (StudentVO studentVO : studentVOList) {
            sidList.add(studentVO.getSid());
        }
        //
        QueryWrapper<StudentScoreEntity> wrapper = new QueryWrapper<StudentScoreEntity>()
                .eq("sid",studentScoreEntity.getSid())
                .eq("is_deleted",0);
        List<StudentScoreEntity> list = studentScoreDao.selectList(wrapper);
        List<Date> timeList = new ArrayList<>();
        for (StudentScoreEntity scoreEntity : list) {
            timeList.add(scoreEntity.getExamTime());
        }
        //判断已有的学号是否包含存入的学号
        if (sidList.contains(studentScoreEntity.getSid())){

            if (timeList.contains(studentScoreEntity.getExamTime())){
                return R.error(500,"考试时间冲突");
            }else {
                this.save(studentScoreEntity);
                return R.ok();
            }
        }else {
            this.save(studentScoreEntity);
            return R.ok();
        }
    }

    @Override
    public void deletedstu(Long[] ids) {
        this.removeByIds(Arrays.asList(ids));
    }

    @Override
    public void updatestu(StudentScoreEntity studentScoreEntity) {
        this.updateById(studentScoreEntity);
    }

    @Override
    public List<SysUserEntity> getuserRealName() {
        List<SysUserEntity> userrealname = baseMapper.queryAllStudent();
        return userrealname;
    }

    //写的查询方法
    public Map<String,Object> selectLike(StudentScoreEntity scoreEntity,String studentName){
        Map<String ,Object> map = new HashMap<>();
        map.put("id",scoreEntity.getId());
        map.put("sid",scoreEntity.getSid());
        map.put("maths",scoreEntity.getMaths());
        map.put("chinese",scoreEntity.getChinese());
        map.put("english",scoreEntity.getEnglish());
        map.put("examTime",scoreEntity.getExamTime());
        map.put("realName",studentName);
        return map;
    }


//    @Override
//    public List<SysUserEntity> getsutdentlist() {
//        List<SysUserEntity> sysUserEntityList = baseMapper.queryAllRealName();
//        return sysUserEntityList;
//    }


}
